<template>
  <Modal
    :open="visible"
    :title="mode === 'create' ? '新增应用' : '编辑应用'"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <Form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <FormItem label="应用名称" name="name">
        <Input v-model:value="formData.name" placeholder="请输入应用名称" />
      </FormItem>

      <FormItem label="应用编码" name="code">
        <Input 
          v-model:value="formData.code" 
          placeholder="请输入应用编码"
          :disabled="mode === 'edit'"
        />
      </FormItem>

      <FormItem label="域名" name="domain">
        <Input v-model:value="formData.domain" placeholder="请输入域名（可选）" />
      </FormItem>

      <FormItem label="租户ID" name="tenant_id">
        <Input v-model:value="formData.tenant_id" placeholder="请输入租户ID" />
      </FormItem>

      <FormItem label="状态" name="is_active">
        <Switch v-model:checked="formData.is_active" />
        <span class="ml-2">{{ formData.is_active ? '启用' : '禁用' }}</span>
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import { Button, Form, FormItem, Input, message, Modal, Switch } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { reactive, ref, watch } from 'vue';

import { exampleAppApi, type ExampleAppItem } from '#/api/example-app';

interface Props {
  visible: boolean;
  data?: ExampleAppItem | null;
  mode: 'create' | 'edit';
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  data: null,
  mode: 'create',
});

const emit = defineEmits<{
  'update:visible': [visible: boolean];
  success: [];
}>();

// 表单引用
const formRef = ref();

// 加载状态
const loading = ref(false);

// 表单数据
const formData = reactive<{
  name: string;
  code: string;
  domain: string;
  tenant_id: string;
  is_active: boolean;
}>({
  name: '',
  code: '',
  domain: '',
  tenant_id: '',
  is_active: true,
});

// 表单验证规则
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 2, max: 50, message: '应用名称长度在 2 到 50 个字符', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入应用编码', trigger: 'blur' },
    { min: 2, max: 20, message: '应用编码长度在 2 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: '应用编码只能包含字母、数字、下划线和横线', trigger: 'blur' },
  ],
  domain: [
    { pattern: /^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: '请输入有效的域名格式', trigger: 'blur' },
  ],
  tenant_id: [
    { required: true, message: '请输入租户ID', trigger: 'blur' },
  ],
};

// 监听数据变化，初始化表单
watch(
  () => props.data,
  (newData) => {
    if (newData && props.mode === 'edit') {
      Object.assign(formData, {
        name: newData.name || '',
        code: newData.code || '',
        domain: newData.domain || '',
        tenant_id: newData.tenant_id || '',
        is_active: newData.is_active ?? true,
      });
    } else {
      // 重置表单
      Object.assign(formData, {
        name: '',
        code: '',
        domain: '',
        tenant_id: '',
        is_active: true,
      });
    }
  },
  { immediate: true }
);

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    loading.value = true;

    if (props.mode === 'create') {
      await exampleAppApi.create({
        name: formData.name,
        code: formData.code,
        domain: formData.domain || undefined,
        tenant_id: formData.tenant_id,
        is_active: formData.is_active,
      });
      message.success('创建成功');
    } else {
      await exampleAppApi.update({
        id: props.data!.id,
        name: formData.name,
        code: formData.code,
        domain: formData.domain || undefined,
        tenant_id: formData.tenant_id,
        is_active: formData.is_active,
      });
      message.success('更新成功');
    }

    emit('success');
    emit('update:visible', false);
  } catch (error) {
    console.error('提交失败:', error);
    message.error('操作失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  emit('update:visible', false);
};
</script>

<style scoped>
.ml-2 {
  margin-left: 8px;
}
</style>